package com.wangyu.talents.web.security.shiro;

import com.wangyu.talents.common.utils.JWTUtil;
import com.wangyu.talents.web.security.shiro.jwt.JWTToken;
import com.wangyu.talents.web.system.user.model.User;
import com.wangyu.talents.web.system.user.utils.UserUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 获取用户的角色和权限信息
 *
 * @author wangyu
 * @Date 2018-09-04 16:05
 */
@Component
public class ShiroRealm extends AuthorizingRealm {

  private Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

  @Override
  public boolean supports(AuthenticationToken token) {
    return token instanceof JWTToken;
  }

  /**
   * 登陆认证
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
      throws AuthenticationException {
    logger.info("登录验证开始");
    String token = (String) authenticationToken.getCredentials();
    String username = JWTUtil.getUserName(token);
    if (username == null || !JWTUtil.verify(token, username)) {
      throw new AuthenticationException("token认证失败！");
    }
    User user = UserUtil.findByUserName(username);
    String password = user.getPassword();
    if (password == null) {
      throw new AuthenticationException("该用户不存在！");
    }

    return new SimpleAuthenticationInfo(token, token, "MyRealm");
  }

  /**
   * 授权认证
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String userName = JWTUtil.getUserName(principals.toString());
    User user = UserUtil.findByUserName(userName);

    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.setRoles(UserUtil.getRoleFlags(user));
    authorizationInfo.setStringPermissions(UserUtil.getPermissions(user));
    return authorizationInfo;
  }
}
